package com.foreveross.proxyip.application.impl.report;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.foreveross.proxyip.application.pool.vo.ExtractLogReportVo;
import com.foreveross.proxyip.application.report.ExtractLogReportApplication;
import com.foreveross.proxyip.entity.ApplyIpLogReportEntity;
import com.foreveross.proxyip.entity.ExtractLogReportEntity;
import com.foreveross.proxyip.infra.PageData;
import com.foreveross.proxyip.infra.base.ddd.repository.IBaseRepository;

@Service
public class ExtractLogReportApplictaionImpl implements ExtractLogReportApplication {
	
	@Resource(name = "entityHibernateRepository")
	IBaseRepository baseRepository;
	@Override
	public PageData searchByConditions(ExtractLogReportVo vo, int pageIndex,
			int pageLen) throws Exception {
		// TODO Auto-generated method stub
		StringBuffer queryStr = new StringBuffer("from ExtractLogReportEntity t where 1=1 ");
		Object[] finalResult = this.generateHqlByConditions(vo);
		queryStr.append(finalResult[0].toString());
		Object [] params = (Object [])finalResult[1];
		List list = baseRepository.queryResult(queryStr.toString(),
				params, pageIndex, pageLen);
		list = list==null?new ArrayList<ApplyIpLogReportEntity>():list;

		long size = this.searchSizeByConditions(vo);
		PageData pageData = new PageData();
		pageData.setDataSize(size);
		pageData.setPageIndex(pageIndex);
		pageData.setPageLen(pageLen);
		pageData.setResult(list);
		int pageCount=(int)size/pageLen+((int)size%pageLen>0?1:0);
		pageData.setPageCount(pageCount);
		vo.setPageData(pageData);
		return null;
	}
	
	private long searchSizeByConditions(ExtractLogReportVo vo)throws Exception{
		StringBuffer hql=new StringBuffer("select count(t) from ExtractLogReportEntity t where 1=1");
		Object[] finalResult=generateHqlByConditions(vo);
		hql=hql.append(finalResult[0].toString());
		Object [] params=(Object [])finalResult[1];
		return baseRepository.queryResultSize(hql.toString(), params);
	}
	
	private Object[] generateHqlByConditions(ExtractLogReportVo vo){
		Object[] finalResult=new Object[2];
		List<Object> params = new ArrayList<Object>();
		
		ExtractLogReportEntity entity = vo.getEt();

		StringBuffer queryStr =  new StringBuffer();
		if (StringUtils.isNotBlank(entity.getExtractMode())) {
			queryStr.append(" and t.extractMode=?");
			params.add(entity.getExtractMode());
		}
		if (StringUtils.isNotBlank(vo.getBeginTime())) {
			queryStr.append(" and t.createTime>=?");
			params.add(vo.getBeginTime());
		}
		if (StringUtils.isNotBlank(vo.getEndTime())) {
			queryStr.append(" and t.createTime<=?");
			params.add(vo.getEndTime());
		}
		finalResult[0] = queryStr;
		finalResult[1] = params.toArray();
		return finalResult;
	}
	
}
